package com.thoughtsFromThePot;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.widget.TextView;

public class servletConnector extends Throwable {

	public servletConnector () {
		
	}
	/**
	 * Posts a thought
	 * @param thought
	 * @param shitter
	 * @return Returns a string. 1 = success 0 = fail
	 */
	public String sendThought(String thought, String shitter, String stallName, String stallPassword)throws TFTPException  {
		JSONObject parameters = new JSONObject();
		JSONObject response = new JSONObject();
		try{
			parameters.put("thought", thought);
			parameters.put("shitter", shitter);
			parameters.put("stallName", stallName);
			parameters.put("stallPassword", stallPassword);
			
			//Call the web service
			response = new JSONObject(callService("GetThoughts.php",parameters));
			
			//If the value of the success key from the response object is true then populate the list
			if(response.get("success").equals("false")){
				throw new TFTPException(response.get("error").toString());
			}
		}
		catch(Exception e){
			System.out.println(e.getMessage());
		}
		return "1";
	}
	
	/**
	 * Retreives a specified number of thoughts and puts them into a thought container
	 * @param numberOfThoughts
	 * @return An ArrayList of thoughtContainer
	 */
	public ArrayList<thoughtContainer> getThoughts(String numberOfThoughts, String stallName, String stallPassword) throws TFTPException, JSONException {
		System.out.println("Servlet connector was called");
		//Connect to the servlet and request all thoughts
		ArrayList<thoughtContainer> tc = new ArrayList<thoughtContainer>();
		//The response of the web service
		JSONObject response; 
		String errorString = null;
		try{
			
			//An individual thought that is put into the thoughtContainer
			JSONObject thought;
			//An array of thoughts
			JSONArray thoughts;
			
			//The parameters sent to the web service
			JSONObject parameters = new JSONObject();
			parameters.put("numberOfThoughts", numberOfThoughts);
			parameters.put("stallName", stallName);
			parameters.put("stallPassword", stallPassword);
			
			int thoughtLengthCounter = 0;
			
			//Call the web service
			System.out.println("Data being sent to server");
			response = new JSONObject(callService("GetThoughts.php",parameters));
			System.out.println("Web service complete");
			
			//If the value of the success key from the response object is true then populate the list
			if(response.get("success").equals("true")){
				thoughts = response.getJSONArray("thoughts");
				while(thoughtLengthCounter<thoughts.length())
	            {
	            	thoughtContainer tempThought = new thoughtContainer();
	            	thought = new JSONObject(thoughts.get(thoughtLengthCounter).toString());
	            	tempThought.setId(Integer.parseInt(thought.get("thoughtNumber").toString()));
	            	tempThought.setDate(thought.get("timeStamp").toString());
	            	tempThought.setThought(thought.get("thought").toString());
	            	tempThought.setUsername(thought.get("shitter").toString());
	            	tempThought.setLikes(Integer.parseInt(thought.get("leaveIt").toString()));
	            	tempThought.setDislikes(Integer.parseInt(thought.get("flushIt").toString()));
	            	tc.add(tempThought);
	            	thoughtLengthCounter++;
	            }
			}
			else{
				errorString = response.get("error").toString();
				throw new TFTPException(response.get("error").toString());
			}
             
		}
		//If it is false then throw an exception
		catch(Exception e){
			System.out.println(e);
			System.out.println("number of thoughts is " + numberOfThoughts);
			System.out.println("stall name is " + stallName);
			System.out.println("stall password is " + stallPassword);
			throw new JSONException(e.getMessage());
		} 
		
		return tc;
	}
	

	/**
	 * Retreives the number of specified thoughts going chronologically backwards from the given thought number
	 * @param numberOfThoughts
	 * @param thoughtNumber
	 * @return An ArrayList of thoughtContainer
	 */
	public ArrayList<thoughtContainer> getThoughts(String numberOfThoughts,int thoughtNumber, String stallName, String stallPassword) throws TFTPException {
		//Connect to the servlet and request all thoughts
		ArrayList<thoughtContainer> tc = new ArrayList<thoughtContainer>();
		//The response of the web service
		JSONObject response; 
		String errorString = null;
		try{
			
			//An individual thought that is put into the thoughtContainer
			JSONObject thought;
			//An array of thoughts
			JSONArray thoughts;
			
			//The parameters sent to the web service
			JSONObject parameters = new JSONObject();
			parameters.put("numberOfThoughts", numberOfThoughts);
			parameters.put("thoughtNumber", thoughtNumber);
			parameters.put("stallName", stallName);
			parameters.put("stallPassword", stallPassword);
			
			int thoughtLengthCounter = 0;
			
			//Call the web service
			response = new JSONObject(callService("MoreThoughts.php",parameters));
			
			//If the value of the success key from the response object is true then populate the list
			if(response.get("success").equals("true")){
				thoughts = response.getJSONArray("thoughts");
				while(thoughtLengthCounter<thoughts.length())
	            {
	            	thoughtContainer tempThought = new thoughtContainer();
	            	thought = new JSONObject(thoughts.get(thoughtLengthCounter).toString());
	            	tempThought.setId(Integer.parseInt(thought.get("thoughtNumber").toString()));
	            	tempThought.setDate(thought.get("timeStamp").toString());
	            	tempThought.setThought(thought.get("thought").toString());
	            	tempThought.setUsername(thought.get("shitter").toString());
	            	tempThought.setLikes(Integer.parseInt(thought.get("leaveIt").toString()));
	            	tempThought.setDislikes(Integer.parseInt(thought.get("flushIt").toString()));
	            	tc.add(tempThought);
	            	thoughtLengthCounter++;
	            }
			}
			else{
				errorString = response.get("error").toString();
				throw new TFTPException(response.get("error").toString());
			}
             
		}
		//If it is false then throw an exception
		catch(Exception e){
			System.out.println(e.getMessage());
		} 
		
		return tc;
		
	}
	
	/**
	 * Retreives the number specified of most left thoughts
	 * @param numberOfThoughts
	 * @return An ArrayList of thoughtContainer
	 */
	public ArrayList<thoughtContainer> getTopThoughts(String numberOfThoughts, String stallName, String stallPassword) throws TFTPException {
		//Connect to the servlet and request all thoughts
		ArrayList<thoughtContainer> tc = new ArrayList<thoughtContainer>();
		//The response of the web service
		JSONObject response; 
		String errorString = null;
		try{
			
			//An individual thought that is put into the thoughtContainer
			JSONObject thought;
			//An array of thoughts
			JSONArray thoughts;
			
			//The parameters sent to the web service
			JSONObject parameters = new JSONObject();
			parameters.put("numberOfThoughts", numberOfThoughts);
			parameters.put("stallName", stallName);
			parameters.put("stallPassword", stallPassword);
			
			int thoughtLengthCounter = 0;
			
			//Call the web service
			response = new JSONObject(callService("TopThoughts.php",parameters));
			
			//If the value of the success key from the response object is true then populate the list
			if(response.get("success").equals("true")){
				thoughts = response.getJSONArray("thoughts");
				while(thoughtLengthCounter<thoughts.length())
	            {
	            	thoughtContainer tempThought = new thoughtContainer();
	            	thought = new JSONObject(thoughts.get(thoughtLengthCounter).toString());
	            	tempThought.setId(Integer.parseInt(thought.get("thoughtNumber").toString()));
	            	tempThought.setDate(thought.get("timeStamp").toString());
	            	tempThought.setThought(thought.get("thought").toString());
	            	tempThought.setUsername(thought.get("shitter").toString());
	            	tempThought.setLikes(Integer.parseInt(thought.get("leaveIt").toString()));
	            	tempThought.setDislikes(Integer.parseInt(thought.get("flushIt").toString()));
	            	tc.add(tempThought);
	            	thoughtLengthCounter++;
	            }
			}
			else{
				errorString = response.get("error").toString();
				throw new TFTPException(response.get("error").toString());
			}
             
		}
		//If it is false then throw an exception
		catch(Exception e){
			System.out.println(e.getMessage());
		} 
		
		return tc;
		
	}
	
	/**
	 * Flushes or leaves a thought
	 * @param thoughtNumber
	 * @param rating
	 * @return A string. 1 if succesful. 0 for fail
	 */
	public String rateThought(int thoughtNumber, int rating, String stallName, String stallPassword) {
		JSONObject parameters = new JSONObject();
		String response = null;
		try{
			parameters.put("thoughtNumber",Integer.toString(thoughtNumber));
			parameters.put("rating",Integer.toString(rating));
			response = callService("Rating.php", parameters);
		}
		catch(Exception e){
			System.out.println(e);
		}
		return response;
	}
	
	/**
	 * Connects to the provided service with the given parameter in a JSONObject format
	 * @param service
	 * @param parameters
	 * @return The response of the web service in a string
	 */
	private String callService(String service, JSONObject parameters) throws Exception{
		String serviceResponse;
		try{
			DefaultHttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://www.thoughtsfromthepot.com/" + service);
			post.setEntity(new StringEntity(parameters.toString()));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			serviceResponse = reader.readLine();
			System.out.println("Web service response is: " + serviceResponse);
			is.close();
		}
		catch(Exception e){
			throw new Exception(e);
		}
		return serviceResponse;
	}
}
